<?php

namespace App\Service\UserService;

use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\VendorClient\Shopcpd\ShopcpdApiClient;
use App\Model\PssModel\PddToken;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\PssModel\Business;
use App\Model\PssLogModel\RpcMicroServiceLog;

/**
 * 理肤泉服务中心
 * @author chenshubo
 */
class LRPService extends BaseService
{

    /**
     * 用户查询
     * @param array $param
     */
    public function userInfo( array $param = [])
    {
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        if(empty($param["mobile"])){
            return Normal::returnCode(Normal::FAIL,"手机号不能为空");
        }
        if(empty($param["accountNo"])){
            return Normal::returnCode(Normal::FAIL,"微信openId不能为空");
        }
        if(empty($param["nickname"])){
            return Normal::returnCode(Normal::FAIL,"昵称不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"LRP理肤泉仓库参数不能为空");
        }
        $data = [];
        $result = (new ShopcpdApiClient($config))->queryMember($param);
        if($result["code"] != Normal::SUC){
            $res= (new ShopcpdApiClient($config))->userRegister($param);
            if($res["code"] != Normal::SUC){
                return $res;
            }
            if($res["data"]["status"] != "SUCCESS"){
                $bindCode = $res["data"]["bindCode"];
                return Normal::returnCode(Normal::FAIL,"注册绑定失败,异常代码为：【{$bindCode}】");
            }
            $data = [
                'cardno'        => $res["data"]["union_code"],
                'marsMemberNum' => $res["data"]["union_code"],
                'unionCode'     => $res["data"]["union_code"],
            ];
        }else{
            $data = [
                'cardno'        => $result["data"]["cardno"],
                'marsMemberNum' => $result["data"]["marsMemberNum"],
                'unionCode'     => $result["data"]["union_code"],
            ];
        }
        //TODO 需要进行结果处理
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }
    
    /**
     * 用户注册
     * @param array $param
     */
    public function userRegister( array $param = [])
    {
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        return (new ShopcpdApiClient($config))->userRegister($param);
    }
    
    /**
     * 查询会员等级
     * @param array $param
     */
    public function queryMemberGrade( array $param = [])
    {
        if(empty($param["queryType"])){
            return Normal::returnCode(Normal::FAIL,"查询类型不能为空");
        }
        if(empty($param["value"])){
            return Normal::returnCode(Normal::FAIL,"值不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"LRP理肤泉仓库参数不能为空");
        }
        $data       =[];
        $gradeCode  =[];
        $tier       =[];
        
        $shopCpdClient = (new ShopcpdApiClient($config));
        
        //查询当前会员等级
        $result = $shopCpdClient->queryMemberGrade($param);
        if($result["code"] != Normal::SUC ){
            $this->addRpcLog("lrpQueryMemberGrade",$param,$result);
            return Normal::returnCode(Normal::FAIL,"查询会员等级失败【{$result['msg']}】",$result);
        }
        
        $MemberGrade = $result["data"];
        
        //查询下一级等级
        $result = $shopCpdClient->queryTierList($param);
        if($result["code"] != Normal::SUC ){
            $this->addRpcLog("lrpQueryTierList",$param,$result);
            return Normal::returnCode(Normal::FAIL,"查询下一级等级失败【{$result['msg']}】",$result);
        }
        
        $queryTierList = $result['data'];
        foreach ($queryTierList as $key => $TierList)
        {
            if( $TierList["tierCode"] == $MemberGrade["gradeCode"]) {
                if($key >1){
                    $tier = $queryTierList[$key-1];
                }else{
                    $tier= $queryTierList[0];
                }
            }
        }
        
        //查询下一级等级还需要消费多少
        $param["grade"]     = $MemberGrade["gradeCode"];
        $param["upGrade"]   = $tier["tierCode"];
        $result = $shopCpdClient->queryMemberGradeCalculator($param);
        if($result["code"] != Normal::SUC ){
            $this->addRpcLog("lrpQueryMemberGradeCalculator",$param,$result);
            return Normal::returnCode(Normal::FAIL,"查询下一级等级消费积分情况失败【{$result['msg']}】",$result);
        }
        $GradeCalculator = $result['data'];
        
        $data = [
            'grade'             => $MemberGrade["grade"],
            'upGrade'           => $tier["tierName"],
            'requiredAmount'    => $GradeCalculator["requiredAmount"],
            'currentAmount'     => $GradeCalculator["currentAmount"],
        ];
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }
    
    /**
     * 查询会员积分
     * @param array $param
     */
    public function queryMemberPoints( array $param = [])
    {
        if(empty($param["queryType"])){
            return Normal::returnCode(Normal::FAIL,"查询类型不能为空");
        }
        if(empty($param["value"])){
            return Normal::returnCode(Normal::FAIL,"值不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"没查到相对应的LRP理肤泉仓库参数");
        }
        $data=[];
        $result= (new ShopcpdApiClient($config))->queryMemberPoints($param);
        $this->addRpcLog("lrpQueryMemberPoints",$param,$result);
        if($result["code"] == Normal::SUC && $result["data"]["points"]){
            foreach ($result["data"]["points"] as $points){
                if($points["pointType"] == "BP"){
                    $data = $points;
                }
            }
        }
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }

    /**
     * 查询会员距离下一个等级还需要多少积分
     * @param array $param
     */
    public function queryMemberGradeCalculator( array $param = [])
    {
        if(empty($param["queryType"])){
            return Normal::returnCode(Normal::FAIL,"查询类型不能为空");
        }
        if(empty($param["value"])){
            return Normal::returnCode(Normal::FAIL,"值不能为空");
        }
        if(empty($param["grade"])){
            return Normal::returnCode(Normal::FAIL,"当前等级不能为空");
        }
        if(empty($param["upGrade"])){
            return Normal::returnCode(Normal::FAIL,"升级等级不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"没查到相对应的LRP理肤泉仓库参数");
        }
        $result =  (new ShopcpdApiClient($config))->queryMemberGradeCalculator($param);
        return $result;
    }
    
    /**
     * 查询会员等级
     * @param array $param
     */
    public function queryTierList( array $param = [])
    {
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"没查到相对应的LRP理肤泉仓库参数");
        }
        $result = (new ShopcpdApiClient($config))->queryTierList($param);
        return $result;
    }
    
    /**
     * 完善会员信息
     * @param array $param
     */
    public function improveMemberInfo( array $param = [])
    {
        if(empty($param["mobile"])){
            return Normal::returnCode(Normal::FAIL,"手机号不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"没查到相对应的LRP理肤泉仓库参数");
        }
        $result = (new ShopcpdApiClient($config))->improveMemberInfo($param);
        $this->addRpcLog("lrpImproveMemberInfo",$param,$result);
        return $result;
    }
    
    /**
     * 上传用户积分
     * @param array $param
     */
    public function uploadOrderInfo( array $param = [])
    {
        if(empty($param["orderSn"])){
            return Normal::returnCode(Normal::FAIL,"orderSn不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        if(empty($param["unionCode"])){
            return Normal::returnCode(Normal::FAIL,"unionCode不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        if(empty($param["orderType"])){
            return Normal::returnCode(Normal::FAIL,"orderType不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        $supplierOrder   = OrderSupplier::instance()
        ->select(OrderSupplier::instance()->order_fields)
        ->where('order_sn',$param["orderSn"])->get()->toArray();
        if( empty($supplierOrder) ) {
            return Normal::returnCode(Normal::FAIL,"当前订单不存在或已支付");
        }
        //获取订单商品
        $osids  = array_column($supplierOrder,'id');
        $orderGoods = OrderSupplierGoods::instance()->select(OrderSupplierGoods::instance()->goods_fields)->whereIn('order_id',$osids)->get()->toArray();
        $data["supplierOrder"] = $supplierOrder;
        $data["orderGoods"]    = $orderGoods;
        $data["unionCode"]     = $param["unionCode"];
        $data["ruid"]          = $param["ruid"];
        $data["orderType"]     = $param["orderType"];
        $result= (new ShopcpdApiClient($config))->uploadOrderInfo($data);
        $this->addRpcLog("lrpUploadOrderInfo",$param,$result);
        return $result;
    }

    /**
     * 会员积分变更
     * @param array $param
     */
    public function changeMemberPoints( array $param = [])
    {
        if(empty($param["queryType"])){
            return Normal::returnCode(Normal::FAIL,"查询类型不能为空");
        }
        if(empty($param["pointType"])){
            return Normal::returnCode(Normal::FAIL,"积分类型不能为空");
        }
        if(empty($param["value"])){
            return Normal::returnCode(Normal::FAIL,"值不能为空");
        }
        if(empty($param["points"])){
            return Normal::returnCode(Normal::FAIL,"积分数量不能为空");
        }
        if(empty($param["changeType"])){
            return Normal::returnCode(Normal::FAIL,"变动方式不能为空");
        }
        if(empty($param["changeSouce"])){
            return Normal::returnCode(Normal::FAIL,"变动渠道不能为空");
        }
        if(empty($param["vender_seq_code"])){
            return Normal::returnCode(Normal::FAIL,"流水号不能为空");
        }
        if(empty($param["remark"])){
            return Normal::returnCode(Normal::FAIL,"备注不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"没查到相对应的LRP理肤泉仓库参数");
        }
        $result =  (new ShopcpdApiClient($config))->changeMemberPoints($param);
        return $result;
    }

    /**
     * 会员积分变更状态查询
     * @param array $param
     */
    public function queryMemberPointChangeStatus( array $param = [])
    {
        if(empty($param["queryType"])){
            return Normal::returnCode(Normal::FAIL,"查询类型不能为空");
        }
        if(empty($param["value"])){
            return Normal::returnCode(Normal::FAIL,"值不能为空");
        }
        if(empty($param["vender_seq_code"])){
            return Normal::returnCode(Normal::FAIL,"流水号不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"没查到相对应的LRP理肤泉仓库参数");
        }
        $result =  (new ShopcpdApiClient($config))->queryMemberPointChangeStatus($param);
        return $result;
    }
    /**
     * 上传兑换信息(新)
     * @param array $param
     */
    public function submitGiftInfo( array $param = [])
    {
        if(empty($param["orderSn"])){
            return Normal::returnCode(Normal::FAIL,"orderSn不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        if(empty($param["vender_seq_code"])){
            return Normal::returnCode(Normal::FAIL,"供应商兑换单流水号不能为空");
        }
        if(empty($param["queryType"])){
            return Normal::returnCode(Normal::FAIL,"会员类型不能为空");
        }
        if(empty($param["value"])){
            return Normal::returnCode(Normal::FAIL,"value不能为空");
        }
        if(empty($param["orderType"])){
            return Normal::returnCode(Normal::FAIL,"orderType不能为空");
        }
        if(empty($param["totalPoints"])){
            return Normal::returnCode(Normal::FAIL,"totalPoints不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        $supplierOrder   = OrderSupplier::instance()
        ->select(OrderSupplier::instance()->order_fields)
        ->where('order_sn',$param["orderSn"])->get()->toArray();
        if( empty($supplierOrder) ) {
            return Normal::returnCode(Normal::FAIL,"当前订单不存在");
        }
        //获取订单商品
        $osids  = array_column($supplierOrder,'id');
        $orderGoods = OrderSupplierGoods::instance()->select(OrderSupplierGoods::instance()->goods_fields)->whereIn('order_id',$osids)->get()->toArray();
        $param["supplierOrder"] = $supplierOrder;
        $param["orderGoods"] = $orderGoods;
        $result= (new ShopcpdApiClient($config))->submitGiftInfo($param);
        $this->addRpcLog("lrpUploadOrderInfo",$param,$result);
        return $result;
    }

    /**
     * 综合查询接口
     * @param array $param
     */
    public function info( array $param = [])
    {
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        if(empty($param["requestRuid"])){
            return Normal::returnCode(Normal::FAIL,"原始请求ruid不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"没查到相对应的LRP理肤泉仓库参数");
        }
        $result =  (new ShopcpdApiClient($config))->info($param);
        return $result;
    }
    /**
     * 订单状态更新接口
     * @param array $param
     */
    public function updateOrderStatus( array $param = [])
    {
        if(empty($param["orderSn"])){
            return Normal::returnCode(Normal::FAIL,"订单号码不能为空");
        }
        if(empty($param["status"])){
            return Normal::returnCode(Normal::FAIL,"订单状态不能为空");
        }
        if(empty($param["ruid"])){
            return Normal::returnCode(Normal::FAIL,"ruid不能为空");
        }
        if(empty($param["cid"])){
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        $config = $this->getLrpConfig($param["cid"]);
        if(empty($config)) {
            return Normal::returnCode(Normal::FAIL,"没查到相对应的LRP理肤泉仓库参数");
        }
        $result =  (new ShopcpdApiClient($config))->updateOrderStatus($param);
        return $result;
    }
    /**
     * 获取系统LRP基础配置
     */
    private function getLrpConfig($cid)
    {
        $businessInfo       = Business::instance()->info(['channel_id'=>$cid]);
        if(empty($businessInfo)){
            return Normal::returnCode(Normal::FAIL,"没找到当前渠道信息");
        }
        $bid        = $businessInfo["id"];
        $pdd_token  = PddToken::instance()->info(['bid'=>$bid]);
        if( empty($pdd_token) ) {
            return []; 
        }
        if($pdd_token["extends"]) {
            return @json_decode($pdd_token['extends'],true);
        }
        return [];
    }
    /**
     * 接收消息进入对应服务层
     * @param array $arguments
     */
    public function addRpcLog( $method, array $message = [] , array $result = [])
    {
        $req_used_time = microtime(true);
        //返回错误的时候才写入日志
        if( $result['code'] != Normal::SUC ) {
            RpcMicroServiceLog::instance()->addLog([
                'interface_code'    => $method,
                'request_url'       => "0.0.0.0",
                'request_param'     => json_encode($message,JSON_UNESCAPED_UNICODE),
                'response_code'     => $result['code'] ?? 0,
                'response_data'     => json_encode($result,JSON_UNESCAPED_UNICODE),
                'req_used_time'     => bcsub((string)microtime(true), $req_used_time,3),
            ]);
        }
    }
}